package com.octopus.controller;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.octopus.conifg.WxConstantConfig;
import com.octopus.util.SignUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/wx")
public class WxPortalController {

    @Autowired
    private WxConstantConfig wxConstantConfig;

    /**
     * 服务器认证接口
     *
     * @param request 请求
     * @param response 响应
     * @throws IOException 异常
     */
    @GetMapping("/auth")
    public void authPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (StrUtil.isNotBlank(request.getParameter("signature"))) {
            String signature = request.getParameter("signature");
            String timestamp = request.getParameter("timestamp");
            String nonce = request.getParameter("nonce");
            String echostr = request.getParameter("echostr");
            log.info("signature[{}], timestamp[{}], nonce[{}], echostr[{}]", signature, timestamp, nonce, echostr);
            if (SignUtil.checkSignature(signature, timestamp, nonce, wxConstantConfig.getFixToken())) {
                log.info("数据源为微信后台，将echostr[{}]返回！", echostr);
                response.getOutputStream().println(echostr);
            }
        }
    }

}
